package smsBean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;
import control.Command;
import control.SpecialCharacter;


import utility.ConvertToLower;
import utility.Index;
import utility.MessageGenerator;


public class SmsTransaction extends SubSmsBean
{
	
	private String masterTable = "transaction";
	private String pl_tableName = "trans_property_details";
	private String td_tableName = "transaction_details";
	
	private SmsTransaction_details std;
	private SmsTrans_property_details stpd ;
	
	private Hashtable<Object,Object> TransactionMap = new Hashtable<Object, Object>() ;
	
	private Hashtable<Object,Object> newTransactionMap = new Hashtable<Object,Object>(); /**  stores new message for Update.*/
	private Hashtable<Object,Object> oldTransactionMap = new Hashtable<Object, Object>(); /** stores old message for Update.*/
	
	//private Transaction_Bean transBean;
	
	Vector<Object> TransPropertyVector = new Vector<Object>();
	Vector<Object> TransDetailVector = new Vector<Object>() ;
	
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	private Hashtable<Object,Object> PropertyViewHashtable = new Hashtable<Object, Object>();
	private Hashtable<Object,Object> TransDetailsViewHashtable = new Hashtable<Object, Object>();
	
	
	/**
	 * In initializeToAdd method of Transaction
	 * put the hashMap in TransactionMap hashtable 
	 * @return TransactionMap is a Hashtable which stores object of Transaction class.
	 * It contains the all the fields of transaction  which presents in 
	 * given message e.g. Transaction_type,seller,buyer etc. 
	 */
	public Hashtable<Object, Object> initializeToAdd() 
	{
		Hashtable<Object, Object> errorHash = new Hashtable<Object, Object>();
		
			ResultSet rs;
			String msg="";
			int index = 0;
			String spchar="";
			String GETPROPERTY="getproperty";
			try
				{
					int start=0;
					rs = sqlDB.getSelect("select fieldname,spchar from command where msgtype = '"+pl_tableName+"' and process = '"+process+"' and order1>0 and spchar is not null order by  order1 ");
					rs.next();
					spchar = rs.getString("spchar");
					if(message.contains(spchar))
					{
						msg = message;
						index = Index.indexOf(message, spchar, index+1);
						msg = message.substring(start,index);
					}
					else 
					{
						try
						{
							rs = sqlDB.getSelect("select fieldname,spchar from command where msgtype = '"+td_tableName+"' and process = '"+process+"' and order1>0 and spchar is not null order by  order1 ");
							rs.next();
							spchar = rs.getString("spchar");
							if(message.contains(spchar))
							{
								msg = message;
								index = Index.indexOf(message, spchar, index+1);
								msg = message.substring(start,index);
							}
							else
							{
								msg = message;
							}						
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
					}									
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			Command cp = new Command(request, sqlDB);	
			TransactionMap = cp.getHashCommand(request,msg,process); 
			TransactionMap=ConvertToLower.convertHashKey(TransactionMap);
		
			if(errorHash.containsKey("ErrorInput"))
			{
				TransactionMap.remove("ErrorInput");
			}				
			
			errorHash = initTransactionProperty();
			if(errorHash.containsKey("ErrorInput"))
			{
				return errorHash;
			}
			
			TransactionMap.put(GETPROPERTY, userid);
			//errorHash =  validate();
			TransactionMap.remove(GETPROPERTY);
			
			Hashtable<Object, Object> ErrorTd= new Hashtable<Object, Object>();
			
			std = new SmsTransaction_details(sqlDB,message,process,request);
			
			//call to Transaction_details initTransaction_details()
			ErrorTd.putAll(std.initTransaction_details());
			
			if(errorHash.containsKey("ErrorInput")||ErrorTd.containsKey("ErrorInput"))
			{
				try 
				{	
					if(!ErrorTd.containsKey("ErrorInput"))
						errorHash.put("ErrorInput", errorHash.get("ErrorInput"));
					else if(!errorHash.containsKey("ErrorInput"))
						errorHash.put("ErrorInput",ErrorTd.get("ErrorInput").toString());
					else
						if(!errorHash.get("ErrorInput").toString().equals(ErrorTd.get("ErrorInput").toString()))
							errorHash.put("ErrorInput", errorHash.get("ErrorInput")+ErrorTd.get("ErrorInput").toString());						
				}
				catch (Exception e) 
				{
					errorHash.putAll(ErrorTd);
				}
			}
			if(errorHash.containsKey("ErrorInput"))
			{
				return errorHash;
			}
			//get vector of trans_property_details
			TransPropertyVector = stpd.getPropertyVector();
			
			//get vector of hashtable of transaction_detail(key as hashtable) & td_property_details(value as vector) 
			TransDetailVector = std.getPropertyVector();
			
			return TransactionMap;
		}
	
	
/**
 * This method initialize the message of Transaction and its properties.
 * pass the message and sqlDB to the costructor of the trans_property_details.
 * initTransactionProperty() invoked by the object of trans_property_details.
 *
 */
	Hashtable<Object, Object>  initTransactionProperty()
	{
		Hashtable<Object, Object> errorHash = new Hashtable<Object, Object>();
		int index=0;
		ResultSet rs;
		String msg="";
		try
		{
			int start=0;
			rs = sqlDB.getSelect("select fieldname,spchar from command where msgtype = '"+td_tableName+"' and process = '"+process+"' and order1>0 and spchar is not null order by  order1 ");
			rs.next();
			String TPropertySPchar = rs.getString("spchar");
			msg = message;
			index = Index.indexOf(message,TPropertySPchar,index+1);
			if(index==-1)
			{
				errorHash.put("ErrorInput","Item should insert");
			}
			msg = message.substring(start,index);
			stpd = new SmsTrans_property_details(sqlDB,msg,process,request);
			
			errorHash = stpd.initTransactionProperty();
			if(errorHash.containsKey("ErrorInput"))
			{
				return errorHash;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return errorHash;
	}
	
	
	
	
	/**
	 * initializeToUpdate() creates two hashtables of old transaction objects to be updated 
	 * to new transaction object respectively  
	 * @return stringbuffer containing details of transaction details updated
	 */
	public StringBuffer initializeToUpdate()
	{
		
		Command cp = new Command(request,sqlDB);
		SpecialCharacter sp=new SpecialCharacter();
		
		ResultSet rs;
		int idIndex=0;
		//String msg1="";
		//String msg2="";

		//int indx1;
		String id=" ",spcharMod = null;//,spcharAdd = null
		/*try
		{
			rs = sqlDB.getSelect("select spchar from command where msgtype = '" + request +"' and process = 'add' order by order1");
			rs.absolute(2);
			spcharAdd = rs.getString("spchar");
			rs.close();
		}
		catch(Exception e)
		{
			System.out.println("SMS::MasterClass::getUpdate():: Exception while fatching special characters ");
			e.printStackTrace();
		}*/
		
		try
		{
			rs = sqlDB.getSelect("select spchar from command where msgtype = '" + request +"' and process = '"+process+"' order by order1");
			rs.next();
			spcharMod = rs.getString("spchar");
			rs.close();
		}
		catch(Exception e)
		{
			System.out.println("SMS::MasterClass::getUpdate():: Exception while fatching special characters ");
			e.printStackTrace();
		}
		
		idIndex = Index.indexOf(message,spcharMod);
		
		if(idIndex!=-1)
		{
			id=message.substring(idIndex+1, sp.getNextSpChar(idIndex, message.toCharArray()));
			
			//changed code  --------			
			try
			{
				String commandMsg = message.substring(idIndex);
				
				newTransactionMap.putAll(cp.getHash(request, commandMsg,process));
				if(newTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(newTransactionMap.toString()+"for process mod in newTransactionMap");
				}
				
				oldTransactionMap.putAll(cp.getHash(request, commandMsg,"add"));
				if(oldTransactionMap.containsKey("ErrorInput"))
			 	{
					return new StringBuffer(oldTransactionMap.toString()+"for process mod in newTransactionMap");
				}
				
				oldTransactionMap.put("id", id);
				newTransactionMap.put("id", id);
			}
			catch (Exception e) {
				// TODO: handle exception
			}			
		}
		else
		{
			sbrDTB.append("Id doesn't exist");
		}
		
		//
		/*try
		{
			
			indx1 =  Index.indexOf(message, spcharAdd);
			
			try
			{
				msg1=message.substring(0,indx1);
				msg2=message.substring(indx1);
			}
			catch (Exception e) {
				msg1=message;
			}		
		
			newTransactionMap.putAll(cp.getHashCommand(request, msg1,process));
			if(newTransactionMap.containsKey("ErrorInput"))
		 	{
				return new StringBuffer(newTransactionMap.toString()+"for process mod in newTransactionMap");
			}
			
			oldTransactionMap.putAll(cp.getHashCommand(request, msg2,"add")); // add 
			
			if(oldTransactionMap.containsKey("ErrorInput"))
		 	{
				return new StringBuffer(oldTransactionMap.toString());
			}
			oldTransactionMap.put("id", id);
			newTransactionMap.put("id", id);
			
		}
		catch(Exception e){}*/
		
		return sbrDTB;
	}
	
	
	/**
	 * initializeToView() creates hashtables of transaction object to be viewed 
	 * @return stringbuffer containing details of transaction to be viewed  
	 */
	public StringBuffer initializeToView() 
	{
	
		StringBuffer sbrProperty=new StringBuffer();
		
		//initialize method return the TransactionMap which contains the tid given in the request
		Command cp=new Command(message,sqlDB);
		Hashtable<Object, Object> TransactionMap = new Hashtable<Object, Object>();
		TransactionMap.putAll(cp.getHashCommand(masterTable, message, process));
		if(TransactionMap.containsKey("ErrorInput"))
		{
			sbrProperty.append(TransactionMap.get("ErrorInput"));
			return sbrProperty;
		}
		
		ViewHashtable.putAll(TransactionMap);
		Hashtable<Object, Object> TransactionHash = new Hashtable<Object, Object>();
		
		//call the view method of trans_property_details through the transaction request.
	
		TransactionHash.putAll(TransactionMap);
		/*TransactionHash.put("tid",TransactionHash.get("id"));
		TransactionHash.remove("id");*/		
		
		SmsTrans_property_details Tpl;
		Tpl = new SmsTrans_property_details(sqlDB,message,process,request);
		
		sbrProperty.append(Tpl.initializeToView());
		PropertyViewHashtable.putAll(Tpl.getViewHashtable());		
		
		//call the view method of transaction_details through the transaction request.
		//View method of transaction_details calls Td_property_details so the StringBuffer which returns 
		//from the view method contain item with its properties.		
		
	    SmsTransaction_details td;
	    td = new SmsTransaction_details(sqlDB,message,process,request);		
		sbrProperty.append(td.initializeToView());
		TransDetailsViewHashtable.putAll(td.getViewHashtable());
		
		return sbrProperty;
		
	}
	
	
	public Hashtable<Object,Object> getHashtable() 	{
		return TransactionMap;
	}
	
	public Vector<Object> getPropertyVector(){	
		return TransPropertyVector;
	}
	
	public Vector<Object> getTransDetailsVector(){
		return TransDetailVector;
	}
	
	public Hashtable<Object, Object> getOldHashtable()	{	
		return (oldTransactionMap);
	}
	
	public Hashtable<Object, Object> getNewHashtable() 	{	
		return (newTransactionMap);
	}
	
	public Hashtable<Object,Object> getViewHashtable() {
		return ViewHashtable;		
	}
	
	public Hashtable<Object,Object> getPropertyViewHashtable() {
		return PropertyViewHashtable;		
	}
	
	public Hashtable<Object,Object> getTransDetailsViewHashtable() {
		return TransDetailsViewHashtable;		
	}


	
	public Hashtable<Object, Object> initializeToDelete() {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * is called when process is to insert in database
	 */
	/*public void setProcessToAdd()
	{	
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		//add	
		//get hashtable of transaction
		TransactionMap.putAll(initializeToAdd());
		
		System.out.println();
		System.out.println("Transaction "+TransactionMap);	
		System.out.println("Transaction pl "+TransPropertyVector);		
		System.out.println("Transaction_details -tdpl "+TransDetailVector);	

		if(!TransactionMap.containsKey("ErrorInput"))
		{
			transBean = new Transaction_Bean();
			
			transBean.setProcess(process);
			transBean.setDBManager(sqlDB);
			transBean.setReqParam(reqParam);
			transBean.setNewHashtable(TransactionMap);
			
			if(!TransPropertyVector.isEmpty())
				transBean.setPropertyVector(TransPropertyVector);
			
			transBean.setTransDetailsVector(TransDetailVector);			
			
			transBean.insert();
		}
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction","processAdd",t.duration());
		
	}*/
	
	
	/**
	 * is called when process is to update in database
	 */
	/*public void setProcessToUpdate()
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();
		//mod	
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToUpdate());
		
		System.out.println("old Transaction "+oldTransactionMap);
		System.out.println("new Transaction "+newTransactionMap);	
			
		transBean = new Transaction_Bean();
		
		transBean.setDBManager(sqlDB);
		transBean.setReqParam(reqParam);
		transBean.setProcess(process);
		
		transBean.setOldHashtable(oldTransactionMap);	
		transBean.setNewHashtable(newTransactionMap);
		
		transBean.update();
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Transaction","processMod",t.duration());
		
	}*/
	
	
	/*@SuppressWarnings("unchecked")
	public void processSms()
	{		
		//add	
		if(process.equalsIgnoreCase("add"))
			processAdd();
		else
			processMod();//mod		
	}
	
	public StringBuffer setProcessToView()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
				
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToView());
		
		System.out.println(ViewHashtable);		
		
		transBean = new Transaction_Bean();
		
		transBean.setDBManager(sqlDB);
		transBean.setReqParam(reqParam);
		transBean.setProcess(process);
		
		transBean.setViewHashtable(ViewHashtable);
		transBean.setPropertyViewHashtable(PropertyViewHashtable);
		transBean.setTransDetailsViewHashtable(TransDetailsViewHashtable);		
		
		sbrDTB.append(transBean.view());
		
		System.out.println(sbrDTB);
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Transaction_details","getView",t.duration());
		
	}
	*/	
	
	public StringBuffer generatesms(StringBuffer strbuffer)
	{
		StringBuffer stringbuffer= new StringBuffer();
		String splitbuffer[] = strbuffer.toString().split("\n");
		if(splitbuffer.length>0)
		{
			try 
			{
				String splitheading[] = splitbuffer[0].split("\t");
				ResultSet rs = sqlDB.getSelect("SELECT fieldname,from_master FROM command where msgtype like 'transaction'"+ " and process='view'" );
				Hashtable<Object , Object> transactionmap = new Hashtable<Object, Object>();
				while(rs.next())
				{	
					transactionmap.put(rs.getString("fieldname"), rs.getString("from_master"));
				}
				StringBuffer heading = new StringBuffer();
				StringBuffer Field = new StringBuffer();
				for(int j=0;j<splitheading.length;j++)
				{
					if(!transactionmap.containsKey(splitheading[j]))
						heading.append(splitheading[j]+"\t");
				}
				
				MessageGenerator msg=new MessageGenerator(sqlDB);
				for(int i=1;i<splitbuffer.length;i++)
				{
					Hashtable<Object , Object> table =new Hashtable<Object, Object>();
				  	String splitfield[] =splitbuffer[i].split("\t");
				  	for(int j=0;j<splitfield.length;j++)
				  	{	
				  		if(transactionmap.containsKey(splitheading[j]))
				  		table.put(splitheading[j],splitfield[j]);
				  		else
				  			Field.append(splitfield[j]+"\t");
				  	}
				  	stringbuffer.append(msg.convertToMessage("transaction","view",table));
				}
				SmsTrans_property_details smstrans_property_details = new SmsTrans_property_details(sqlDB);
				stringbuffer.append(smstrans_property_details.generatesms(heading.append("\n"+Field)));
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		}
		return stringbuffer;
	}
}
